<?php

namespace app\admin\controller;

use app\model\File;
use Qiniu\Auth;
use Qiniu\Config;
use think\facade\Db;
use think\facade\Request;
use \app\model\Video;
use \app\model\Oss;

class Batch extends Common
{

    public function lists()
    {
//        echo strtotime(date('2021-01-01'));exit;
        $params = Request::param();

        $page = $this->page;

        $arr = array('title' => 'like', 'phone' => 'like', 'order_no' => 'like', 'trade_no' => 'like', 'is_onsale' => '=', 'id' => '=', 'code' => '=', 'pay_type' => '=', 'status' => '=', 'cat_id' => '=', 'vip_time' => 'gtNow');

        $sql_where = "A.is_delete = 0";

        foreach ($arr as $k => $v) {
            if (isset($params[$k]) && $params[$k] !== '') {

                $val = $params[$k];
                if ($v === 'like') {
                    $val = "%" . $params[$k] . "%";
                }

                if ($v === 'gtNow') {
                    if ($val === '1') {
                        $sql_where .= " AND A." . $k . " > " . "'" . date("Y-m-d") . "'";
                    } else {
                        $sql_where .= " AND (A." . $k . " <= '" . date("Y-m-d") . "' OR A." . $k . " is NULL)";
                    }
                } else {
                    $sql_where .= " AND A." . $k . " " . $v . " '" . $val . "'";
                }

                //echo $sql_where;exit;
            }
        }

        $addtime = getParam($params, 'addtime');

        if ($addtime) {
            $addtimes = explode(',', $addtime);
            $sql_where .= " AND A.addtime BETWEEN '" . $addtimes[0] . "' AND '" . $addtimes[1] . "'";
        }
        // echo $sql_where;exit;


        $sql_order = getSqlOrder("A." . getParam($params, 'ordField'), getParam($params, 'ordOrder'), "A.id DESC");

        //  echo $sql_order;

        $pageSize = getParam($params, 'pageSize', 15);

        $currentPage = getParam($params, 'currentPage', 1);

        $limit_start = $pageSize * ($currentPage - 1);

        $limit_end = $pageSize * $currentPage;

        $limit = getParam($params, 'limit');

        if ($limit) {
            $limit_start = 0;
            $limit_end = 100;
        }

        if ($page === 'goods') {
            $subsql = Db::name('chapters')
                ->field('gid,count(id)  chapter_count')
                ->buildSql();

            $sql_field = 'A.title,A.id,A.price,A.cover,A.is_onsale,A.addtime,A.ord,B.title as cat_title,C.chapter_count';
            $lists = Db::name($page)->alias('A')->field($sql_field)
                ->leftJoin('kt_goods_cats B', 'B.id = A.cat_id')->leftJoin([$subsql => 'C'], 'A.id = C.gid')
                ->where($sql_where)->order($sql_order)->limit($limit_start, $limit_end)->select()->toArray();
//        echo  Db::name($page)->getlastsql();exit;
        } else if ($page === 'chapters') {
            $lists = $this->getChapters($page, $sql_where, $sql_order);
        } else if ($page === 'cdkey') {
            $lists = $this->getCdkeys($page, $sql_where, $sql_order, $limit_start, $limit_end);
        } else if ($page === 'news') {
            $lists = $this->getNews($page, $sql_where, $sql_order, $limit_start, $limit_end);
        } else if ($page === 'pay') {
            $sql_where = str_replace("A.phone", "B.phone", $sql_where) . " AND A.is_pay = 1";

            $lists = $this->getPay($page, $sql_where, $sql_order, $limit_start, $limit_end);
            $count = Db::name($page)->alias('A')->leftJoin('kt_users B', 'B.id = A.uid')->where($sql_where)->count();
            listsJson($lists, $count);
            return;
        } else {

            $lists = Db::name($page)->alias('A')->where($sql_where)->order($sql_order)->limit($limit_start, $limit_end)->withoutField('pwd')->select()->toArray();
        }

        //  echo Db::name($page)->getLastSql();
        $count = Db::name($page)->alias('A')->where($sql_where)->count();

        listsJson($lists, $count);
    }

    public function posts()
    {
        $page = $this->page;


        $params = Request::except(['page', 'id']);

        $id = Request::param('id');

        if ($id) {
            $info = Db::name($page)->where("id=" . $id)->find();
        }

        $fields = Db::name($page)->getTableFields();

        $sql_where = "";

        if (in_array('uid', $fields)) {
            $sql_where = " AND uid = " . $this->userId;
            $params['uid'] = $this->userId;
        }

        $is_update_qiuniu = 0;

        $paramsUrl = isset($params['url']) ? $params['url'] : '';
        if ($page === 'material' && $paramsUrl) {
            if ($id && isset($info['url']) && $info['url'] === $paramsUrl) {

            } else {
                $params['duration'] = Video::getInfo($this->config['qiniu_domain'] . $paramsUrl);

                $params['file_size'] = File::getRemoteSize($this->config['qiniu_domain'] . $paramsUrl);
                $is_update_qiuniu = 1;
            }


        }
        if ($page === 'vips') {
            $params['times'] = $params['duration'] * 3600 * 24 * 30;

        }

        if ($id) {
            if ($page === 'users') {
                if (isset($params['pwd']) && $params['pwd']) {
                    $params['pwd'] = md5(md5($params['pwd']));
                }
                if (!$params['vip_time']) {
                    $params['vip_time'] = null;
                }
            }

            Db::name($page)->where("id=" . $id . $sql_where)->update($params);
            $lastId = $id;
        } else {

            $lastId = Db::name($page)->insertGetId($params);
            $is_update_qiuniu = 1;
        }

        // 更新七牛云

        if (strstr($paramsUrl, 'temp')) {
            $fileName = basename($paramsUrl);
            $extendName = substr($fileName, strrpos($fileName, '.') + 1);
            $destKey = 'material/' . getFileBei($lastId) . $lastId . '/' . md5($lastId . "_knowledge") . "." . $extendName;  //文件名

            $this->move($paramsUrl, $destKey, $lastId);
            Db::name($page)->where("id=" . $lastId)->update(array('url' => $destKey));
        }
        $coverUrl = isset($params['cover']) ? $params['cover'] : '';
        $coverPages = array('goods','material');

        if (strstr($coverUrl, 'temp') && in_array($page,$coverPages)) {

            $fileName = basename($coverUrl);
            $extendName = substr($fileName, strrpos($fileName, '.') + 1);
            $destKey = $page.'/' . getFileBei($lastId) . $lastId."." . $extendName;  //文件名
//            echo $coverUrl."<hr>";
//            echo $destKey;exit;
            $this->move($coverUrl, $destKey, $lastId);
            Db::name($page)->where("id=" . $lastId)->update(array('cover' => $this->config['qiniu_domain'] .$destKey));
        }

        singleJson($lastId, '出错');
    }

    public function move($key, $destKey, $id)
    {
        $key = str_replace($this->config['qiniu_domain'],"",$key);
//        echo $key;
//        echo $destKey;
//        exit;
        if (!$key) {
            singleJson(false, '没有文件file');
        }
        if (!$id) {
            singleJson(false, '没有id');
        }
        $accessKey = $this->config['qiniu_accessKey'];
        $secretKey = $this->config['qiniu_secretKey'];
        $bucket = $this->config['qiniu_bucket'];

        $auth = new Auth($accessKey, $secretKey);
        $config = new Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        $err = $bucketManager->move($bucket, $key, $bucket, $destKey, true);
//        print_r($destKey);
//    print_r($err);
    }

    public function detail()
    {
        $page = $this->page;

        $params = Request::param();

        $id = getParam($params, 'id');

        $detail = Db::name($page)->where("id=" . $id)->withoutField('pwd')->find();

        singleJson($detail, '出错');
    }

    public function delete()
    {

        $params = Request::param();
        $id = getParam($params, 'id');

        $pagesDelete = array('chapters_materials');

        if ($id) {
            if (in_array($this->page, $pagesDelete)) {
                Db::name($this->page)->where("id=" . $id . "")->delete();
            } else {
                Db::name($this->page)->where("id=" . $id . "")->update(array('is_delete' => 1));
            }

        }
        singleJson(true, '出错');
    }

    public function switchField()
    {

        $params = Request::param();
        $id = getParam($params, 'id');
        $field = getParam($params, 'field');
        $value = getParam($params, 'value') || 0;
        if ($id) {
            Db::name($this->page)->where("id=" . $id . " AND uid = " . $this->userId)->update(array($field => $value));

        }
        singleJson(true, '出错');
    }

    public function update()
    {

        $params = Request::param();
        $ids = getParam($params, 'ids');
        $field = getParam($params, 'field');
        $value = getParam($params, 'value') || 0;
        if ($ids) {
            Db::name($this->page)->where("id IN (" . $ids . ")")->update(array($field => $value));

        }
        singleJson(true, '出错');
    }

    public function ord()
    {

        $params = Request::param();
        $id = getParam($params, 'id');

        if ($id) {
            Db::name($this->page)->where("id=" . $id)->update(array('ord' => $params['ord']));
            //  echo Db::name('goods')->getlastsql();

        }
        singleJson(true, '出错');
    }

    public function getChapters($page, $sql_where, $sql_order)
    {
        $sql_field = 'A.title,A.id,A.is_onsale,A.ord';
        $lists = Db::name($page)->alias('A')->field($sql_field)
            ->where($sql_where)->order($sql_order)->select()->toArray();
        foreach ($lists as $k => $v) {
            $lists[$k]['materials'] = Db::name('chapters_materials')->alias('A')->field("A.ord,A.id,B.title,B.cover,B.type,B.is_try,B.is_onsale")
                ->leftJoin('kt_material B', 'B.id = A.material_id	')
                ->where("A.chapter_id=" . $v['id'])->order("A.ord ASC")->select()->toArray();

        }
        return $lists;
    }


    public function getCdkeys($page, $sql_where, $sql_order, $limit_start, $limit_end)
    {
        $sql_field = 'A.title,A.id,A.code,A.status,A.use_uid as uid,A.use_date,B.phone';
        $lists = Db::name($page)->alias('A')->field($sql_field)->leftJoin('kt_users B', 'B.id = A.use_uid')
            ->where($sql_where)->order($sql_order)->limit($limit_start, $limit_end)->select()->toArray();

        return $lists;
    }

    public function getPay($page, $sql_where, $sql_order, $limit_start, $limit_end)
    {
        $sql_field = 'A.uid,A.id,A.title,A.type,A.order_no,A.order_money,A.trade_no,A.pay_type,A.update_date,B.phone';

        $lists = Db::name($page)->alias('A')->field($sql_field)->leftJoin('kt_users B', 'B.id = A.uid')
            ->where($sql_where)->order($sql_order)->limit($limit_start, $limit_end)->select()->toArray();

        return $lists;
    }

    public function getNews($page, $sql_where, $sql_order, $limit_start, $limit_end)
    {
        $sql_field = 'A.title,A.id,A.cat_id,A.ord,B.title as cat_title';
        $lists = Db::name($page)->alias('A')->field($sql_field)->leftJoin('kt_news_cats B', 'B.id = A.cat_id')
            ->where($sql_where)->order($sql_order)->limit($limit_start, $limit_end)->select()->toArray();

        return $lists;
    }
}
